package com.sum.tea.ui

import android.app.KeyguardManager
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.PowerManager
import android.text.Spannable
import android.text.SpannableString
import android.text.style.AbsoluteSizeSpan
import android.view.View
import android.widget.Toast
import androidx.core.content.getSystemService
import com.blankj.utilcode.constant.PermissionConstants
import com.blankj.utilcode.util.PermissionUtils
import com.blankj.utilcode.util.SPUtils
import com.sum.common.manager.UHFManager
import com.sum.common.panling.PowerUtils
import com.sum.common.utils.SoundUtils
import com.sum.tea.base.BaseMvvmActivity
import com.sum.tea.R
import com.sum.tea.adapter.MyFragmentAdapter
import com.sum.tea.constant.Constants
import com.sum.tea.databinding.ActivityMainBinding
import com.sum.tea.viewmodel.MainViewModel
import com.xuexiang.xui.utils.WidgetUtils
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog
import kotlin.system.exitProcess

class MainActivity : BaseMvvmActivity<ActivityMainBinding, MainViewModel>() {

//    private lateinit var mMiniLoadingDialog: MiniLoadingDialog
    private var lastClickTime = 0L
    private lateinit var wakeLock: PowerManager.WakeLock
    private lateinit var keyguardLock: KeyguardManager.KeyguardLock
    private var isPowerOff = false


    override fun initView(savedInstanceState: Bundle?) {
        checkAndRequestPermission()
        PowerUtils.getInstance().setPowerOn(true)
        initSystemServices()
        initViews()
        initSoundPool()
        initViewPager()
        observeViewModel()
//        mMiniLoadingDialog = WidgetUtils.getMiniLoadingDialog(this)
        mViewModel.connectReader()
    }
    private fun initActionBar() {
        supportActionBar?.let { actionBar ->
            val spannableString = SpannableString("UHF_DEMO").apply {
                setSpan(
                    AbsoluteSizeSpan(15, true),
                    0,
                    length,
                    Spannable.SPAN_EXCLUSIVE_INCLUSIVE
                )
            }
            actionBar.title = spannableString
        }
    }

    private fun createObserver() {
        mBinding.loading.visibility=View.GONE
        mBinding.loadingBar.visibility = View.VISIBLE
        mBinding.loadingText.visibility = View.VISIBLE
    }

    private fun initSystemServices() {
        val powerManager = getSystemService<PowerManager>()
        wakeLock = powerManager?.newWakeLock(
            PowerManager.FULL_WAKE_LOCK,
            "MyApp:WakeLock"
        ) ?: throw IllegalStateException("PowerManager not available")

        val keyguardManager = getSystemService<KeyguardManager>()
        keyguardLock = keyguardManager?.newKeyguardLock("MyApp:KeyguardLock")
            ?: throw IllegalStateException("KeyguardManager not available")
    }


    private fun initViews() {
        setupActionBar()
        setupClickListeners()
    }

    private fun setupActionBar() {
        supportActionBar?.apply {
            title = SpannableString("UHF_DEMO").apply {
                setSpan(
                    AbsoluteSizeSpan(15, true),
                    0,
                    length,
                    Spannable.SPAN_EXCLUSIVE_INCLUSIVE
                )
            }
        }
    }

    private fun setupClickListeners() {
        with(mBinding) {
            tvLabel.setOnClickListener { updatePageSelection(0) }
            tvSetting.setOnClickListener { updatePageSelection(1) }
            tvReadwritelock.setOnClickListener { updatePageSelection(2) }
        }
    }

    private fun initSoundPool() {
        SoundUtils.initSoundPool(this)
    }

    private fun initViewPager() {
        val fragments = listOf(
            LabelFragment(),
            SettingFragment(),
            ReadWriteLockFragment()
        )

        mBinding.viewPager.apply {
            adapter = MyFragmentAdapter(supportFragmentManager, fragments)
            setSwipeEnabled(false)
            currentItem = 0
        }
    }

    private fun observeViewModel() {
            mViewModel.connectionStatus.observe(this) { isConnected ->
//            mMiniLoadingDialog.dismiss()
                val message = if (isConnected) {
                    createObserver()
                    restorePower()
                    R.string.Connection_successful
                } else {
                    R.string.Connection_failed
                }
                Toast.makeText(this, getString(message), Toast.LENGTH_SHORT).show()
            }
        mViewModel.currentPage.observe(this) { position ->
            mBinding.viewPager.currentItem = position
            updateTabColors(position)
        }

        mViewModel.soundEnabled.observe(this) { enabled ->
            if (enabled) {
                SoundUtils.playSound()
            }
        }
    }

    private fun updatePageSelection(position: Int) {
        mViewModel.setCurrentPage(position)
    }

    // Reset power to the value stored in SharedPreferences
    private fun restorePower(){
        val power = SPUtils.getInstance().getInt(Constants.KEY_POWER)
        if(power != -1){
            UHFManager.getInstance().currentManager.setPower(power)
        }
    }

    private fun checkAndRequestPermission() {
        PermissionUtils.permissionGroup(PermissionConstants.STORAGE)
            .callback(object : PermissionUtils.FullCallback {
                override fun onGranted(permissionsGranted: List<String>) {

                }

                override fun onDenied(permissionsDeniedForever: List<String>,
                                      permissionsDenied: List<String>) {

                }
            })
            .request()
    }

    private fun updateTabColors(position: Int) {
        with(mBinding) {
            val activeColor = Color.parseColor("#add8e6")
            val inactiveColor = Color.LTGRAY

            tvLabel.setBackgroundColor(if (position == 0) activeColor else inactiveColor)
            tvSetting.setBackgroundColor(if (position == 1) activeColor else inactiveColor)
            tvReadwritelock.setBackgroundColor(if (position == 2) activeColor else inactiveColor)
        }
    }

    override fun onResume() {
        super.onResume()
        wakeLock.acquire()
        keyguardLock.disableKeyguard()
    }

    override fun onPause() {
        super.onPause()
        wakeLock.release()
        keyguardLock.reenableKeyguard()
    }

    override fun onBackPressed() {
        val currentTime = System.currentTimeMillis()
        if (currentTime - lastClickTime < 2000) {
            super.onBackPressed()
            mViewModel.closeReader()
            PowerUtils.getInstance().setPowerOn(false)
            finishAndRemoveTask()
            exitProcess(0)
        } else {
            Toast.makeText(this, getString(R.string.msgExit), Toast.LENGTH_SHORT).show()
        }
        lastClickTime = currentTime
    }

}